const express = require("express")
const router = express.Router()
const Building = require("../models/building")

// 获取所有楼栋
router.get("/getBuildings", async (req, res) => {
  try {
    const buildings = await Building.findAll({
      where: { delete_at: null },
      order: [["create_at", "DESC"]],
    })
    res.json({ code: 200, data: buildings, message: "获取楼栋列表成功" })
  } catch (error) {
    res.json({ code: 500, message: "获取楼栋列表失败" })
  }
})

// 添加楼栋
router.post("/addBuilding", async (req, res) => {
  try {
    const building = await Building.create(req.body)
    res.json({ code: 200, data: building, message: "添加楼栋成功" })
  } catch (error) {
    res.json({ code: 500, message: "添加楼栋失败" })
  }
})

// 更新楼栋
router.put("/updateBuilding/:id", async (req, res) => {
  try {
    const building = await Building.findByPk(req.params.id)
    if (!building) return res.json({ code: 404, message: "楼栋不存在" })
    await building.update(req.body)
    res.json({ code: 200, message: "更新楼栋成功" })
  } catch (error) {
    res.json({ code: 500, message: "更新楼栋失败" })
  }
})

// 删除楼栋（软删除）
router.delete("/deleteBuilding/:id", async (req, res) => {
  try {
    const building = await Building.findByPk(req.params.id)
    if (!building) return res.json({ code: 404, message: "楼栋不存在" })
    await building.update({ delete_at: new Date() })
    res.json({ code: 200, message: "删除楼栋成功" })
  } catch (error) {
    res.json({ code: 500, message: "删除楼栋失败" })
  }
})

module.exports = router
